package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.*;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.PurchaseListService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author WZhaokang
 * @date 2020/12/29 13:51
 */
@Service
public class PurchaseListServiceImpl implements PurchaseListService {

    @Autowired
    private PurchaseListDao purchaseListDao;
    @Autowired
    private PurchaseListGoodsDao purchaseListGoodsDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private UserDao userDao;

    /**
     * 保存进货单
     * @param purchaseList
     * @return
     */
    @Override
    @Transactional
    public int save(PurchaseList purchaseList,String purchaseListGoodsStr) {
        //保存purchaseList
        int save = purchaseListDao.save(purchaseList);

        PurchaseListGoods[] purchaseListGoods = new Gson().fromJson(purchaseListGoodsStr, PurchaseListGoods[].class);
        List<PurchaseListGoods> listGoods = Arrays.asList(purchaseListGoods);//保存这个集合
        //保存进货单，具体某一个商品
        for (PurchaseListGoods listGood : listGoods) {
            listGood.setPurchaseListId(purchaseList.getPurchaseListId());
            int save1 = purchaseListGoodsDao.save(listGood);
            System.out.println(listGood);

            //更新库存商品库存(添加)
            //商品的id在ListGoods中
            //查询
            Goods good = goodsDao.findByGoodsId(listGood.getGoodsId());
            good.setInventoryQuantity(listGood.getGoodsNum() + good.getInventoryQuantity());
            goodsDao.updateGoods(good);
        }
        if (save > 0 && save >0){
            return 1;
        }
        return 0;
    }

    /**
     *
     * @param purchaseNumber  进货单号
     * @param supplierId    供应商id
     * @param state         订单状态
     * @param sTime     区间段
     * @param eTime     区间段
     * @return
     */
    @Override
    public List<PurchaseList> list(String purchaseNumber, Integer supplierId, Integer state, String sTime, String eTime) {
        //时间段，t_purchase_list因为这个里面有个时间 收获时间purchase_date
        List<PurchaseList> purchaseLists = purchaseListDao.list(purchaseNumber,supplierId, state,sTime,eTime);
        return purchaseLists;
    }

    @Override
    public void updateState(Integer purchaseListId) {
        PurchaseList purchaseList = purchaseListDao.selectByPurchaseListId(purchaseListId);
        purchaseListDao.updateState(purchaseListId,1);
    }
}
